package com.atguigu.gmall.auth.service.impl;

import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.auth.service.AuthService;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.AuthException;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@EnableConfigurationProperties(JwtProperties.class)
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private GmallUmsClient umsClient;

    @Autowired
    private JwtProperties jwtProperties;

    //实行单点登录
    @Override
    public void login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {

        try {
            //查询用户
            ResponseVo<UserEntity> userEntityResponseVo = umsClient.query(loginName, password);
            UserEntity userEntity = userEntityResponseVo.getData();

            //判断用户是否存在
            if (userEntity == null) {
                //用户不存在
                throw new AuthException("登录信息有误!");
            }
            //组装载荷 userId userName
            Map<String, Object> map = new HashMap<>();
            map.put("userId",userEntity.getId());
            map.put("userName",userEntity.getUsername());

            // 添加ip地址防止盗用
            String ip = IpUtils.getIpAddressAtService(request);
            map.put("ip",ip);

            //生成token
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire());

            //将token存入cookie中
            CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getExpire() * 60);

            //为了判断页面登录状态 向cookie中添加 unick: unick
            CookieUtils.setCookie(request,response,"unick",userEntity.getUsername(),jwtProperties.getExpire() * 60);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthException("登录信息有误!");
        }
    }
}
